<template>
  <div>
    <!-- show-checkbox 展示复选框 -->
    <!-- check-strictly 切断父子级列表的双向绑定关联 -->
    <el-tree
      ref="tree"
      node-key="id"
      show-checkbox
      :data="list"
      check-strictly
      default-expand-all
      :props="{label:'name'}"
    />
    <div class="footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="hSubmit">确认</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
import { assignPermission, getRolesDetail } from '@/api/roles'
export default {
  name: 'Assignpermission',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissions()
    this.loadPermissionsDetail()
  },

  methods: {
    async loadPermissions() {
      const res = await getPermissionList()
      // console.log(res)
      this.list = tranListToTreeData(res.data)
    },
    async loadPermissionsDetail() {
      const res = await getRolesDetail(this.id)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    async hSubmit() {
      try {
        const ids = this.$refs.tree.getCheckedKeys()
        // console.log(ids)
        const res = await assignPermission({ id: this.id, permIds: ids })
        console.log(res)
        this.$message.success(res.message)
        this.$emit('close')
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .footer {
    display: flex;
    justify-content: end;
  }
</style>
